'use strict';

angular.module('afasApp')
  .controller('StudentsCtrl', ['$scope', 'Services', '$state', '$modal', '$stateParams', '$filter', '_', function ($scope, Services, $state, $modal, $stateParams, $filter, _) {

    // VARIABLE
    $scope.students            = [];
    $scope.studentNew          = {
      Sex: 0
    };
    $scope.studentNew.Contacts = [];
    $scope.psForm              = false;
    $scope.psFormNew           = false;
    $scope.occupations         = [];
    $scope.contactResults      = [];
    $scope.selectedContacts    = [];
    $scope.results             = {};
    $scope.errors              = {};

    // Contacts

    $scope.contacttypes = [];
    $scope.cities = [];
    $scope.contactNew = {};
    $scope.contactNew.City = {};
    $scope.contactNew.ContactType = {};
    $scope.contactNew.errors = {};

    // SEARCH FUNCTION
    $scope.searchKey = $stateParams.key;
    $scope.searchText = $scope.searchKey;
    $scope.params = {
      'keyword': $scope.searchText,
      'is_valid': true,
      'include': 'all,latest_placement_test,latest_enrollment,contacts'
    };
    $scope.searchStudent = function() {
      $state.go( '^.searchList', {key: $scope.searchText} );
    };

    if ($stateParams.name) {
      $scope.studentNew.FullName = $stateParams.name;
    };

    // OCCUPATION
    // Services.getItems('occupations')
    // .then(function(results){
    //   $scope.occupations = results.data;
    // });

    // PAGINATION
    $scope.pagesize = 10;

    $scope.pagination = {
      current: 1
    };

    $scope.pageChanged = function(newPage) {
      getResultsPage(newPage);
    };

    function getResultsPage(pageNumber) {
      var data = $scope.params;
      data.pagesize = $scope.pagesize;
      data.page = (pageNumber - 1);
      $scope.pagination.current = pageNumber;
      Services.getItems('students', data)
      .then(function( results ) {
        var pagingData = angular.fromJson(results.headers['x-pagination']);
        $scope.totalItems = pagingData.TotalCount;
        $scope.students = results.data;
      });
    }

    if ($stateParams.key) {
      getResultsPage(1);
    };

    // FUNCTION
    $scope.addStudent = function () {
      $scope.errors = {};
      $scope.studentNew.DoB = $filter('date')($scope.timepicker.timeA, 'yyyy-MM-dd');
      if ($scope.studentNew.Contacts.length < 1) {
        delete $scope.studentNew.Contacts;
      };
      console.log($scope.studentNew);

      Services.add('students', $scope.studentNew)
      .then(function(results){
        // $scope.studentNew = {};
        $scope.results = results.data;
        $state.go( '^.searchList', {key: $scope.studentNew.FullName} );
      }, function(results){
        console.log(results);
        if (results.status == 400) {
          $scope.errors = results.data;
          if (!angular.isArray($scope.studentNew.Contacts)) {
            // delete $scope.studentNew.Contacts;
            $scope.studentNew.Contacts = [];
          };
        }
      });
    };

    $scope.deleteStudent = function (student) {
      Services.delete('students', student)
      .then(function(){
        // loadRemoteData();
      });
    };

    // ADD NEW STUDENT
    $scope.searchContacts = function (val) {
      $scope.contactResults = [];
      var params = {
        'keyword' : val,
        'is_valid': true,
        'pageSize': 10,
        'include' : 'all,contacts'
      };

      return Services.getItems('students', params)
      .then(function(results){
        $scope.contactResults = [];
        angular.forEach(results.data, function(value, key){
          angular.forEach(value.Contacts, function(val, k){
            var contactData = {};
            contactData = val;
            var temp = value;
            delete temp.Contacts;
            contactData.Student = temp;
            $scope.contactResults.push(contactData);
          })
        })
        return $scope.contactResults;
      });
    };

    $scope.selectContact = function (contact) {
      // console.log(contact);
      $scope.studentNew.Contacts.push(contact);
      $scope.selectedContacts.push(contact.Id);
    };

    $scope.removeContact = function (ct) {
      console.log(ct);
      $scope.selectedContacts = _.without($scope.selectedContacts, ct.Id);
      $scope.studentNew.Contacts = _.without($scope.studentNew.Contacts, ct);
    };

    $scope.valid = function (contact) {
      // console.log(contact);
      // console.log(_.contains($scope.studentNew.Contacts, contact));
      return !(_.contains($scope.selectedContacts, contact.Id));
    };

    $scope.onSelect = function ($item, $model, $label) {
      console.log($item);
      if (!_.contains($scope.selectedContacts, $item.Id)) {
        $scope.studentNew.Contacts.push($item);
        $scope.selectedContacts.push($item.Id);
        $scope.customSelected = '';
      }
    };

    $scope.addNewContact = function(){
      $scope.psFormNew = true;

      Services.getItems($scope.CONTACTTYPE_URL)
      .then(function(results){
        $scope.contacttypes = results.data;
      });

      Services.getItems('cities')
      .then(function(results){
        $scope.cities = results.data;
      });
    };

    $scope.addContact = function(){
      $scope.errors = {};
      Services.add('contacts', $scope.contactNew)
      .then(function(results){
        // console.log($scope.contact);
        // $scope.contact.Id = 0;

        // studentNew.Contacts.push($scope.contact);
        $scope.studentNew.Contacts.push(results.data);
        $scope.contactNew = {};
        $scope.psFormNew = false;
      }, function(results){
        if (results.status == 400) {
          $scope.errors = results.data;
        }
      });
      // $modalInstance.dismiss('cancel');
    };

    $scope.disactivate = function(id){
      var data = {
        'IsValid': false
      };

      Services.update('students', data, id)
      .then(function(results){
        $scope.item = results.data;
        $state.go($state.current, {'key': $scope.searchText}, {reload: true});
      }, function(results){
        if (results.status == 400) {
          $scope.errors = results.data;
        }
      });
    }

    $scope.openDetailedModal = function (id) {

      var modalInstance = $modal.open({
        templateUrl: 'myModalDetailedStudent.html',
        controller: DetailModalCtrl,
        resolve: {
          studentId: function () {
            return id;
          }
        }
      });
      modalInstance.result.then(function (selectedItem) {
        // payment.discounts = selectedItem;
      }, function () {
        console.log('Modal dismissed at: ' + new Date());
      });

    };
  }])
  .controller('StudentsBlockedCtrl', ['$scope', 'Services', '$state', '$modal', '$stateParams', '_', function ($scope, Services, $state, $modal, $stateParams, _) {

    $scope.students = [];
    $scope.searchKey = $stateParams.key;
    $scope.searchText = $scope.searchKey;

    function applyRemoteData( newData ) {
      $scope.students = newData;
    }

    function loadRemoteData() {
      Services.getItems('students')
      .then(function( results ) {
        applyRemoteData( results.data );
      });
    }

    loadRemoteData();

    $scope.searchStudent = function() {
      $state.go( '^.searchBlocked', {key: $scope.searchText} );
    };
  }])
  .controller('StudentsRefundCtrl', ['$scope', '$rootScope', 'Services', '$state', '$modal', '$stateParams', '_', function ($scope, $rootScope, Services, $state, $modal, $stateParams, _) {

    $scope.refunds = [];
    $scope.selectedRefunds = [];
    $scope.searchKey = $stateParams.key;
    $scope.searchText = $scope.searchKey;

    $scope.params = {
      'include'     : 'all'
    };

    // PAGINATION
    $scope.pagesize = 10;

    $scope.pagination = {
        current: 1
    };

    $scope.pageChanged = function(newPage) {
      getResultsPage(newPage);
    };

    function getResultsPage(pageNumber) {
      var data = $scope.params;
      data.pagesize = $scope.pagesize;
      data.page = (pageNumber - 1);
      $scope.pagination.current = pageNumber;
      Services.getItems('refunds', data)
      .then(function( results ) {
        var pagingData = angular.fromJson(results.headers['x-pagination']);
        $scope.totalItems = pagingData.TotalCount;
        $scope.refunds = results.data;
      });
    }
    getResultsPage(1);

    $scope.checkSelected = function(Id) {
      return _.where($scope.selectedRefunds, { Id: Id }).length > 0;
    };

    $scope.toggleRefund = function(refund) {
      console.log(refund);
      var items = _.where($scope.selectedRefunds, {Id: refund.Id});
      var item = _.findWhere($scope.selectedRefunds, {Id: refund.Id});

      if (items.length > 0) {
        $scope.selectedRefunds = _.without($scope.selectedRefunds, item);
      } else {
        $scope.selectedRefunds.push(refund);
      }
    };

    $scope.proceedRefund = function(){
      angular.forEach($scope.selectedRefunds, function(value, index){
        value.Status = 2;

        Services.update('refunds', value, value.Id)
        .then(function(results){
          // $scope.psDiscounts = false;
        }, function (results) {
          if (results.status == 400) {
            $scope.errors = results.data;
          }
        })
      });
    };

    $scope.cancelRefund = function(){
      angular.forEach($scope.selectedRefunds, function(value, index){
        value.Status = 5;

        Services.update('refunds', value, value.Id)
        .then(function(results){
          // $scope.psDiscounts = false;
        }, function (results) {
          if (results.status == 400) {
            $scope.errors = results.data;
          }
        })
      });
    };

    $scope.reBank = function(){
      angular.forEach($scope.selectedRefunds, function(value, index){
        value.Status = 6;

        Services.update('refunds', value, value.Id)
        .then(function(results){
          // getResultsPage(1);
        }, function (results) {
          if (results.status == 400) {
            $scope.errors = results.data;
          }
        })
      });
    };

  }])
  .controller('StudentsUnpaidCtrl', ['$scope', 'Services', '$state', '$modal', '$stateParams', '_', function ($scope, Services, $state, $modal, $stateParams, _) {

    $scope.students = [];
    $scope.searchKey = $stateParams.key;
    $scope.searchText = $scope.searchKey;

    function applyRemoteData( newData ) {
      $scope.students = newData;
    }

    function loadRemoteData() {
      Services.getItems('students')
      .then(function( results ) {
        applyRemoteData( results.data );
      });
    }

    loadRemoteData();

    $scope.searchStudent = function() {
      $state.go( '^.searchUnpaid', {key: $scope.searchText} );
    };
  }])
  .controller('StudentsDiscountCtrl', ['$scope', 'Services', '$state', '$modal', '$stateParams', '_', function ($scope, Services, $state, $modal, $stateParams, _) {

    $scope.discounts = [];
    $scope.searchKey = $stateParams.key;
    $scope.searchText = $scope.searchKey;
    $scope.params = {
      'is_valid': true
    };

    // PAGINATION
    $scope.pagesize = 10;

    $scope.pagination = {
      current: 1
    };

    $scope.pageChanged = function(newPage) {
      getResultsPage(newPage);
    };

    function getResultsPage(pageNumber) {
      var data = $scope.params;
      data.pagesize = $scope.pagesize;
      data.page = (pageNumber - 1);
      $scope.pagination.current = pageNumber;
      Services.getItems('student_discounts', data)
      .then(function( results ) {
        console.log(results.headers);
        var pagingData = angular.fromJson(results.headers['x-pagination']);
        $scope.totalItems = pagingData.TotalCount;
        $scope.discounts = results.data;
      });
    }
    getResultsPage(1);

    $scope.searchStudent = function() {
      $state.go( '^.searchDiscount', {key: $scope.searchText} );
    };
  }])
  .controller('StudentCtrl', ['$scope', 'Services', '$state', '$stateParams', '$filter', '_', function ($scope, Services, $state, $stateParams, $filter, _) {

    console.log(_);
    $scope.psForm = false;
    $scope.psFormNew = false;
    $scope.psFormEdit = false;

    $scope.currentStudent = {};
    $scope.item = {};
    $scope.currentContact = {};
    $scope.contactNew = {};
    $scope.currentID = $stateParams.id;
    // $scope.sexes = [];
    $scope.occupations = [];
    $scope.selectedContacts    = [];
    $scope.contactResults = [];
    $scope.contacttypes = [];
    $scope.cities = [];

    $scope.params = {
      'include': 'all,enrollments,occupation,placement_tests,make_up_tests,latest_placement_test,latest_enrollment,contacts,student_logs'
    }

    Services.getItem('students', $scope.currentID, $scope.params)
    .then(function(results){
      $scope.currentStudent = results.data;
      $scope.item = results.data;
      $scope.currentStudent.DoB = $filter('date')($scope.currentStudent.DoB, 'yyyy-MM-dd HH:mm:ss');
      // $scope.currentStudent.DoB = new Date($scope.currentStudent.DoB);
      if ($scope.currentStudent.Contacts.length > 0) {
        angular.forEach($scope.currentStudent.Contacts, function(value, key){
          $scope.selectedContacts.push(value.Id);
        });
      } else {
        $scope.currentStudent.Contacts = [];
      }

      // OCCUPATION
      Services.getItems('occupations', { 'getall': 'true', 'is_valid': 'true', 'order_by': 'order', 'order_type': 'ASC' })
      .then(function(results){
        $scope.occupations = results.data;
      });
    });

    // ADD NEW STUDENT
    $scope.searchContacts = function (val) {
      $scope.contactResults = [];
      var params = {
        'keyword' : val,
        'pageSize': 5,
        'include' : 'all,contacts'
      };
      return Services.getItems('students', params)
      .then(function(results){
        $scope.contactResults = [];
        angular.forEach(results.data, function(value, key){
          angular.forEach(value.Contacts, function(val, k){
            var contactData = {};
            contactData = val;
            var temp = value;
            delete temp.Contacts;
            contactData.Student = temp;
            $scope.contactResults.push(contactData);
          })
        })
        return $scope.contactResults;
      });
    };

    $scope.selectContact = function (contact) {
      $scope.currentStudent.Contacts.push(contact);
      $scope.selectedContacts.push(contact.Id);
    };

    $scope.removeContact = function (ct) {
      console.log(ct);
      $scope.selectedContacts = _.without($scope.selectedContacts, ct.Id);
      $scope.currentStudent.Contacts = _.without($scope.currentStudent.Contacts, ct);
    };

    $scope.valid = function (contact) {
      // console.log(contact);
      // console.log(_.contains($scope.currentStudent.Contacts, contact));
      return !(_.contains($scope.selectedContacts, contact.Id));
    };

    $scope.onSelect = function ($item, $model, $label) {
      if (!_.contains($scope.selectedContacts, $item.Id)) {
        $scope.currentStudent.Contacts.push($item);
        $scope.selectedContacts.push($item.Id);
        $scope.customSelected = '';
      }
    };

    $scope.addNewContact = function(){
      $scope.psFormNew = true;

      if ($scope.contacttypes.length < 1) {
        Services.getItems($scope.CONTACTTYPE_URL)
        .then(function(results){
          $scope.contacttypes = results.data;
        });
      };

      if ($scope.cities.length < 1) {
        Services.getItems('cities')
        .then(function(results){
          $scope.cities = results.data;
        });
      };
    };

    $scope.editContact = function(ct){
      $scope.psFormEdit = true;
      console.log($scope.psFormEdit);
      $scope.currentContact = ct;

      if ($scope.contacttypes.length < 1) {
        Services.getItems($scope.CONTACTTYPE_URL)
        .then(function(results){
          $scope.contacttypes = results.data;
        });
      };

      if ($scope.cities.length < 1) {
        Services.getItems('cities')
        .then(function(results){
          $scope.cities = results.data;
        });
      };
    };

    $scope.reset = function(){
      $scope.psFormNew = false;
      $scope.psFormEdit = false;
    }

    $scope.updateContact = function(){
      $scope.errors = {};
      Services.update('contacts', $scope.currentContact, $scope.currentContact.Id)
      .then(function(results){
        // console.log($scope.contact);
        // $scope.contact.Id = 0;

        // studentNew.Contacts.push($scope.contact);
        // $scope.currentStudent.Contacts.push(results.data);
        $scope.currentContact = {};
        $scope.psFormEdit = false;
      }, function(results){
        if (results.status == 400) {
          $scope.errors = results.data;
        }
      });
      // $modalInstance.dismiss('cancel');
    };

    $scope.addContact = function(){
      $scope.errors = {};
      Services.add('contacts', $scope.contactNew)
      .then(function(results){
        // console.log($scope.contact);
        // $scope.contact.Id = 0;

        // studentNew.Contacts.push($scope.contact);
        $scope.currentStudent.Contacts.push(results.data);
        $scope.contactNew = {};
        $scope.psFormNew = false;
      }, function(results){
        if (results.status == 400) {
          $scope.errors = results.data;
        }
      });
      // $modalInstance.dismiss('cancel');
    };

    $scope.updateStudent = function () {
      // Students.updateStudent($scope.currentStudent, $scope.currentID);
      var data = $scope.currentStudent;
      data.DoB = $filter('date')($scope.currentStudent.DoB, 'yyyy-MM-dd');

      delete data.Enrollments;
      delete data.PlacementTests;
      delete data.LatestEnrollment;
      delete data.Invoices;
      // console.log(data);

      Services.update('students', data, $scope.currentID)
      .then(function(results){
        $scope.item = results.data;
        $state.transitionTo('^', {id: $scope.currentID}, {
          reload: true,
          inherit: false,
          notify: true
        }, function(results){
          if (results.status == 400) {
            $scope.errors = results.data;
          }
        });
      });
    };

    //datepicker

    // $scope.getSR = function(id) {

    // };
  }])
  .controller('StudentReportCtrl', ['$scope', 'Services', '$state', '$stateParams', '$filter', '_', function ($scope, Services, $state, $stateParams, $filter, _) {

    console.log(_);

    $scope.enrollment = {};
    $scope.currentID = $stateParams.id;

    $scope.params = {
      'include': 'all,assessments,student'
    }

    Services.getItem('enrollments', $scope.currentID, $scope.params)
    .then(function(results){
      $scope.enrollment = results.data;
    });
  }]);